<?php

namespace catchAdmin\permissions\model;

use catchAdmin\permissions\model\search\DepartmentSearch;
use catcher\base\CatchModel;
use think\db\exception\DbException;
use catcher\Utils;
use app\common\model\BaseModel;

class Department extends CatchModel
{
    use DepartmentSearch;
    use DataRangScopeTrait;

    protected $name = 'departments';

    protected $field = [
        'id', //
        'department_name', // 部门名称
        'parent_id', // 父级ID
        'principal', // 负责人
        'mobile', // 联系电话
        'email', // 联系又想
        'creator_id', // 创建人ID
        'status', // 1 正常 2 停用
        'sort', // 排序字段
        'created_at', // 创建时间
        'updated_at', // 更新时间
        'deleted_at', // 删除状态，null 未删除 timestamp 已删除
    ];

    protected $updateChildrenFields = 'status';

    /**
     * 列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getList($type = 1): array
    {
        $deptIds = (new BaseModel())->getDeptListByUser([]);

        $where = [];
        $where[] = ['id', '>', 0];
        if ($type == 2) {
            $where[] = ['status', '=', 1];
        }
        if (!empty($deptIds)) {
            $deptList = $this->where('status', '=', 1)->select()->toArray();
            foreach ($deptIds as $k => $value) {
                $topLevelIds = $this->getParentDepartmentId($value, $deptList);
                $deptIds = array_merge($deptIds, $topLevelIds);
            }
            $deptIds = array_unique($deptIds);
            $where[] = ["id", "in", $deptIds];
        }
        $res = $this->catchSearch()
            ->where($where)
            ->catchOrder()
            ->select();

        if ($this->enterSearch === false) {
            return $res->toTree();
        }
        return $res->toArray();
    }

    /**
     * 获取子部门IDS
     *
     * @time 2020年11月04日
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws DbException
     */
    public static function getChildrenDepartmentIds($id)
    {
        $departmentIds = Department::field(['id', 'parent_id'])->select()->getAllChildrenIds([$id]);

        $departmentIds[] = $id;

        return $departmentIds;
    }

    public function getParentDepartmentId($parentId, $categories): array
    {
        $topLevelIds = [];

        foreach ($categories as $category) {
            if ($category['id'] == $parentId) {
                if (isset($category['parent_id'])) {
                    $topLevelIds = array_merge($topLevelIds, $this->getParentDepartmentId($category['parent_id'], $categories));
                }
                $topLevelIds[] = $category['id'];
            }
        }

        return $topLevelIds;
    }
    public function getDeptByIds(array $deptIds): array
    {
        if (empty($deptIds)) {
            return [];
        }
        // 获取每个子数组的最后一个元素
        $lastElements = array_map(function ($subArray) {
            return end($subArray);
        }, $deptIds);
        if (!empty($lastElements)) {
            $deptList = $this->where("id", "in", $lastElements)->field(["id", "department_name"])->select();
            return $deptList ?$deptList->toArray(): [];
        }
        return [];
    }

    /**
     * 按权限获取科室
     * @time 2023年03月31日
     * @return array
     */
    public function getDepartments()
    {

        if (!Utils::isSuperAdmin()) {
            $role = (new BaseModel())->getDeptListByUser([]);

            if (!empty($role)) {
                return $this->whereIn('id', $role)->order('created_at', 'desc')->select();
            }

        }
        return $this->order('created_at', 'desc')->select()->toTree();
    }
}
